
package cnhy.salary.controller;

import cnhy.salary.domain.Department;
import cnhy.salary.domain.UserRef;
import cnhy.salary.domain.dto.EmployeeDto;
import cnhy.salary.service.EmployeeSvc;
import cnhy.salary.service.M3HandlerSvc;
import com.easy.query.core.api.dynamic.sort.ObjectSort;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import cnhy.salary.domain.Employee;
//import cnhy.salary.service.EmployeeService;
import ling.common.*;
import ling.common.domain.*;
import org.springframework.web.multipart.MultipartFile;

/** 员工 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-5-26
 */
@Api(tags = "员工 功能接口")
@RestController
@RequestMapping("/salary/Employee")
public class EmployeeController extends EQueryController<Employee> {

    @Resource
    ISysUserService sysUserService;

    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.employee.query)")
    @GetMapping(value = "/{id}")
    public Result<EmployeeDto> getInfo(@PathVariable("id") Long id) {
        var entity = queryHelper.queryable(EmployeeDto.class).where(e -> e.eq(EmployeeDto::getId, id)).firstOrNull();
        return Result.ok(entity);
    }

    @ApiOperation("分页列表")
    @PreAuthorize("@ps.any(@pay.employee.list)")
    @GetMapping("list")
    @DataScope
    public ResultRows<EmployeeDto> list(EmployeeDto dto, PageSort pageRequest) {
        var data = queryPage2(dto, pageRequest);
        return data;
    }

    @ApiOperation(value = "查看人员扩展")
    //@PreAuthorize("@ps.any(@pay.employee.list)")
    @GetMapping("list2")
    public ResultRows<EmployeeDto> list2(EmployeeDto dto, PageSort pageRequest) {
        return queryPage2(dto, pageRequest);
    }

    @Override
    protected ResultRows<Employee> queryPage(Serializable whereObj, PageDomain pageRequest) {

        var data = queryPage2(whereObj, pageRequest);

        return (ResultRows) data;
    }


    protected ResultRows<EmployeeDto> queryPage2(Serializable whereObj, PageDomain pageRequest) {
        gainPageDomain(pageRequest);

        //
        var dto = (Employee) whereObj;
        Long[] deptIds = null;

        var pitem = queryHelper.query().queryable(EmployeeDto.class)
                .where(e -> e.isNotNull(EmployeeDto::getId))
                .where(deptIds != null, e -> e.in(EmployeeDto::getDeptId, deptIds))
                .where(dto.getResign()!=null&&dto.getResign()==0,p->p.isNull(EmployeeDto::getResignTime))
                .where(dto.getResign()!=null&&dto.getResign()==1,p->p.isNotNull(EmployeeDto::getResignTime))
                .whereObject(dto != null, dto);
        if (pageRequest instanceof ObjectSort)
            pitem.orderByObject((ObjectSort) pageRequest);

        var pData = pitem
                .orderByAsc(p->p.column(EmployeeDto::getOrderNum))
                .orderByDesc(p -> p.column(EmployeeDto::getId))
                .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());

        return toResultRows(pData);
    }

    @ApiOperation(value = "查看我的部门管辖人员", notes = "需当前人员为部门领导，返回本部门所有人员,包含自己")
    @GetMapping("myDeptEmpls")
    public ResultRows<EmployeeDto> myDeptEmpls(EmployeeDto dto, PageSort pageRequest) {
        gainPageDomain(pageRequest);

        var dept = queryHelper.entityQuery(Department.class).whereById(getDeptId()).firstOrNull();
        if (!Objects.equals(dept == null ? null : dept.getLeaderId(), getUserId()) && !SecurityUtils.isAdmin(getUserId())) {
            return ResultRows.bad("无权限,需部门领导才可查看本部门员工信息");
        }
        var pitem = queryHelper.query().queryable(EmployeeDto.class)
                .where(e -> e.isNotNull(EmployeeDto::getId))
                // .where(e -> e.ne(EmployeeDto::getUserId,getUserId()))
                .whereObject(dto != null, dto)
                .where(!SecurityUtils.isAdmin(getUserId()), p -> p.eq(EmployeeDto::getDeptId, getDeptId()));
        pitem.orderByObject(pageRequest);
        var pData = pitem.orderByDesc(p -> p.column(EmployeeDto::getId)).toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        return toResultRows(pData);
    }

    @ApiOperation(value = "新增员工", notes = "新增时会先创建系统用户，然后建立员工并关联用户")
    @PreAuthorize("@ps.any(@pay.employee.add)")
    @Log(title = "员工", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public Result add(@Validated @RequestBody Employee entity) {
        return employeeSvc.addEmployees(true, entity);
    }

    @Resource
    EmployeeSvc employeeSvc;

    private Result addEmployee(Employee entity) {

        if (StringUtils.isBlank(entity.getJobNum()))
            return Result.bad("工号不能为空");
        var old = queryHelper.entityQuery(Employee.class).where(e -> e.jobNum().eq(entity.getJobNum())).firstOrNull();
        if (old != null)
            return Result.bad("工号重复");
        var user = new SysUser();
        user.setUserName(entity.getJobNum());
        user.setNickName(entity.getName());
        user.setStatus("0");
        user.setCreateTime(new Date());
        user.setCreateBy(getUsername());
        sysUserService.insertUser(user);
        //queryHelper.query().insertable(entity).executeRows(true);
        entity.setUserId(user.getUserId());
        return null;
    }


    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.employee.remove)")
    @Log(title = "员工", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids) {
        return super.remove(Arrays.stream(ids).toArray());
    }

    @ApiOperation(value = "编辑", notes = "部门调整后会移除原领导职务")
    @PreAuthorize("@ps.any(@pay.employee.edit)")
    @Log(title = "员工", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public Result edit(@Validated @RequestBody Employee entity) {
        var re = super.edit(entity);
        var user = queryHelper.queryable(UserRef.class).whereById(entity.getUserId()).firstOrNull();
        if (!Objects.equals(user.getDeptId(), entity.getDeptId()) && user.getDeptId() != null) {
            var dept = queryHelper.entityQuery(Department.class)
                    .whereById(user.getDeptId())
                    .where(d -> d.leaderId().eq(user.getUserId()))
                    .firstOrNull();
            if (dept != null) {
                dept.setLeaderId(null);
                dept.setLeader(null);
                queryHelper.entityQuery().updatable(dept).executeRows();
            }
        }
        user.setDeptId(entity.getDeptId());
        queryHelper.queryClient().updatable(user).executeRows();
        return re;
    }

    @ApiOperation(value = "离职", notes = "只需要id,离职状态状态设定后，会将对应user账户设置为停用")
    @PreAuthorize("@ps.any(@pay.employee.edit)")
    @Log(title = "员工", businessType = BusinessType.UPDATE)
    @PostMapping("resign/{ids}")
    public Result resign(@PathVariable("ids") Long[] ids) {
        var id = ids[0];
        return employeeSvc.resign(id);
    }
    @ApiOperation(value = "复职", notes = "只需要id,离职状态变为正常在职")
    @PreAuthorize("@ps.any(@pay.employee.edit)")
    @Log(title = "员工", businessType = BusinessType.UPDATE)
    @PostMapping("reinstated/{userId}")
    public Result reinstated(@PathVariable("userId")Long userId) {

        return employeeSvc.reinstated(userId);
    }

    ISysUserService userService;

    @ApiOperation("导出")
    @PreAuthorize("@ps.any(@pay.employee.export)")
    @Log(title = "员工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(Employee entity, PageDomain pageRequest, HttpServletResponse response) {
        super.export(entity, pageRequest, null, response);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public Result importData(MultipartFile file) throws Exception {
        var util = new ExcelUtil<>(Employee.class);
        var list = util.importExcel(file.getInputStream());
        return employeeSvc.addEmployees(true, list.toArray(new Employee[0]));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Employee> util = new ExcelUtil<>(Employee.class);
        util.importTemplateExcel(response, "员工导入模板");
    }


    @Resource
    M3HandlerSvc m3HandlerSvc;

    @PostMapping("/deleteMember")
    public Result deleteMember(Long[] ids) {
        var list=new ArrayList<>();
        ids=doubleIds;
        for (var id : ids) {
            var re = m3HandlerSvc.deleteMember(id);
            if (!re.isSuccess() || !re.getData()) {
                list.add(id);
            }
        }
        return Result.ok(list);
    }

    Long[] doubleIds=new Long[]{
            1839148255099748392L,
            1839148289451098140L
    };
}